package test;

import jpcap.*;
import jpcap.packet.Packet;
import jpcap.packet.TCPPacket;

public class Tcpdump implements PacketReceiver {

	public void receivePacket(Packet packet) {
		if (packet instanceof TCPPacket) {
     		TCPPacket tcpPacket = (TCPPacket) packet;
//			System.out.println(tcpPacket.dst_ip+":"+tcpPacket.dst_port);
//			System.out.println(new String(tcpPacket.data));
//			System.out.println(bytesToHexStr(tcpPacket.data));
			if (tcpPacket.dst_port == 1111){
				//System.out.println(new String(tcpPacket.data));
				System.out.println(bytesToHexStr(tcpPacket.data));
				
			}
		}
	}

	public static String bytesToHexStr(byte[] s) {
		String res = "";
		for (int i = 0; i < s.length; i++) {
			res = res + " " + String.format("%02X", s[i] & 0xff);
		}
		return res;
	}

	public static void main(String[] args) throws Exception {
		NetworkInterface[] devices = JpcapCaptor.getDeviceList();
		int index=0;
		if (devices.length>1)
			index=1;
		JpcapCaptor jpcap = JpcapCaptor.openDevice(devices[index], 2000, true, 20);
		//
		//jpcap.setFilter("tcp dst port 10000", true);
		jpcap.loopPacket(-1, new Tcpdump());
	}

	/**
	 * 
	 * @param devices
	 */
	public void enumNetInterface(NetworkInterface[] devices) {
		System.out
				.println("usage: java Tcpdump <select a number from the following>");
		for (int i = 0; i < devices.length; i++) {
			System.out.println(i + " :" + devices[i].name + "("
					+ devices[i].description + ")");
			System.out.println("    data link:" + devices[i].datalink_name
					+ "(" + devices[i].datalink_description + ")");
			System.out.print("    MAC address:");
			for (byte b : devices[i].mac_address)
				System.out.print(Integer.toHexString(b & 0xff) + ":");
			System.out.println();
			for (NetworkInterfaceAddress a : devices[i].addresses)
				System.out.println("    address:" + a.address + " " + a.subnet
						+ " " + a.broadcast);
		}
	}
}
